const axios = require('axios');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const FormData = require('form-data');

const API_BASE_URL = 'http://api.ctdy123.com/users';

async function addNewVersion(version, platform, filePath, releaseNotes) {
    try {
        // 創建 FormData
        const formData = new FormData();
        formData.append('version', version);
        formData.append('platform', platform);
        formData.append('releaseNotes', releaseNotes);
        formData.append('installer', fs.createReadStream(filePath));

        // 發送請求
        const response = await axios.post(`${API_BASE_URL}/add-version`, formData, {
            headers: {
                ...formData.getHeaders()
            },
            maxContentLength: Infinity,
            maxBodyLength: Infinity
        });

        console.log('Version added successfully:', response.data);
    } catch (error) {
        console.error('Error adding version:', error.response?.data || error.message);
    }
}

async function listVersions(platform) {
    try {
        const response = await axios.get(`${API_BASE_URL}/version-history`);
        const versions = response.data.versions;
        
        // 過濾平台
        const filteredVersions = platform 
            ? versions.filter(v => v.platform === platform)
            : versions;

        // 按版本號排序
        filteredVersions.sort((a, b) => b.version.localeCompare(a.version));

        // 格式化輸出
        console.log('\nVersion History:');
        console.log('================');
        filteredVersions.forEach(v => {
            console.log(`\nVersion: ${v.version}`);
            console.log(`Platform: ${v.platform}`);
            console.log(`Release Date: ${new Date(v.releaseDate).toLocaleString()}`);
            console.log(`Download URL: ${v.downloadUrl}`);
            console.log(`MD5: ${v.md5}`);
            console.log('Release Notes:');
            console.log(v.releaseNotes);
            console.log('----------------');
        });
    } catch (error) {
        console.error('Error listing versions:', error.response?.data || error.message);
    }
}

async function deleteVersion(version, platform) {
    try {
        const response = await axios.delete(`${API_BASE_URL}/delete-version`, {
            data: { version, platform }
        });
        console.log('Version deleted successfully:', response.data);
    } catch (error) {
        console.error('Error deleting version:', error.response?.data || error.message);
    }
}

async function checkUpdate(currentVersion, platform) {
    try {
        const response = await axios.post(`${API_BASE_URL}/check-update`, {
            currentVersion,
            platform
        });
        
        if (response.data.message === 'No update available') {
            console.log('You are using the latest version.');
        } else {
            console.log('\nNew version available:');
            console.log(`Version: ${response.data.version}`);
            console.log(`Platform: ${response.data.platform}`);
            console.log(`Download URL: ${response.data.downloadUrl}`);
            console.log('\nRelease Notes:');
            console.log(response.data.releaseNotes);
        }
    } catch (error) {
        console.error('Error checking update:', error.response?.data || error.message);
    }
}

// 命令行接口
const command = process.argv[2];
switch (command) {
    case 'add':
        const [version, platform, filePath, ...notes] = process.argv.slice(3);
        if (!version || !platform || !filePath) {
            console.log('Usage: node version-manager.js add <version> <platform> <filePath> <releaseNotes>');
            process.exit(1);
        }
        addNewVersion(version, platform, filePath, notes.join(' '));
        break;

    case 'list':
        const platformFilter = process.argv[3];
        listVersions(platformFilter);
        break;

    case 'delete':
        const delVersion = process.argv[3];
        const delPlatform = process.argv[4];
        if (!delVersion || !delPlatform) {
            console.log('Usage: node version-manager.js delete <version> <platform>');
            process.exit(1);
        }
        deleteVersion(delVersion, delPlatform);
        break;

    case 'check':
        const checkVersion = process.argv[3];
        const checkPlatform = process.argv[4];
        if (!checkVersion || !checkPlatform) {
            console.log('Usage: node version-manager.js check <currentVersion> <platform>');
            process.exit(1);
        }
        checkUpdate(checkVersion, checkPlatform);
        break;

    default:
        console.log('Usage:');
        console.log('  Add version:    node version-manager.js add <version> <platform> <filePath> <releaseNotes>');
        console.log('  List versions:  node version-manager.js list [platform]');
        console.log('  Delete version: node version-manager.js delete <version> <platform>');
        console.log('  Check update:   node version-manager.js check <currentVersion> <platform>');
} 